<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\api\controller\KbxOrder;
use think\Db;
use app\admin\model\Poi as poiModel;
use app\api\controller\Poi as PController;
use app\admin\model\City as cityModel;
use app\admin\model\ArticleCate as cateModel;
use app\admin\model\Member as MemberModel;
use app\api\model\Poi as PoiAPi;
use app\api\controller\OssController as OSSApi;
use think\Request;
use think\Cookie;
use app\api\controller\Common;
use app\api\controller\KbxOther;

use app\admin\model\GeoHash;

class Poi extends User
{
    public function index()
    {
        //修改页面 20210428
        return $this->fetch('expediacity/country');

        $country=array();
        $citys=array();

        $city = Db::name('city c')
            ->join('continent co','c.continentid=co.id','left')
            ->field('c.*,co.name as continent_name,co.eng_name as continent_eng_name')
            ->order("sort_weight desc")->select();

        for ($x=0; $x<count($city); $x++) {
            if(empty($city[$x]['groupid'])){
                array_push($country,$city[$x]);
            }
        }

        for ($x=0; $x<count($country); $x++) {
            array_push($citys,$country[$x]);
            for ($y=0; $y<count($city); $y++) {
                if(!empty($city[$y]['groupid'])&&$city[$y]['groupid']==$country[$x]['id']){
                    array_push($citys,$city[$y]);
                }
            }
        }


        $this->assign('city',$citys);
        return $this->fetch();
    }

    public function citypoi()
    {
        $post = $this->request->post();
        $where['deleted']=0;
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['name'] = ['like', '%' . $post['cityname'] . '%'];
        }
        //查询所有国家ID
        $country = db('city')->where(['groupid'=>0,'deleted'=>0])->column('id');
        $where['groupid'] = ['gt',0];
        $city = Db::name('city')->where($where)->order("sort_weight desc")->select();
        //城市的所属国家存在
        foreach ($city as $city_key=>$city_value){
            if(!in_array($city_value['groupid'],$country)){
                unset($city[$city_key]);
            }
        }

        //统计个城市下的POI数量
        $poi_classify_id = db('classify')->select();
        $poi_classify_id = array_column($poi_classify_id,'classify_id');
        $pois = db('poi')->field('count(id) as num,groupid')->where([
            'deleted'=>0,
            'typeid'=>['in',$poi_classify_id]
        ])->group('groupid')->select();
        foreach ($city as $city_key=>$city_value){
            $city[$city_key]['poinum'] = 0;
            foreach ($pois as $poi_key=>$poi_value){
                if($city_value['id']==$poi_value['groupid']){
                    $city[$city_key]['poinum'] = $poi_value['num'];
                    break;
                }
            }
        }

        $this->assign('city',$city);
        return $this->fetch();
    }

    public function poisee()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 0;
        $name=Db::name('city')->where('id',$id)->select();
        $nearspots=array();

        //查询classify名称
        $classify_info = Db::name("classify")->select();
        $classify_name = array();
        foreach ($classify_info as $c_value) {
            $classify_name[$c_value['classify_id']] = $c_value['classify_name'];
        }
        //初始化类型和数量统计
        $classify_list = db('classify')->field('classify_id,classify_name')->where(['is_use'=>1])->select();
        $type_ids = array_column($classify_list,'classify_id');

        $post = $this->request->post();
        if (isset($post['name']) and !empty($post['name'])) {
            $where['name|eng_name'] = ['like', '%' . $post['name'] . '%'];
            $this->assign('wherelist',$post);
        }
        $where['groupid']=$id;
        $where['deleted']=0;

        if($typeid){
            $poi=Db::name('poi')
                ->where($where)
                ->where("typeid",'eq',$typeid)
                ->order('update_time desc,poi_sort desc')
                ->select();
        }else{
            $poi=Db::name('poi')
                ->where($where)
                ->where(['typeid'=>['in',$type_ids]])//7未知 8三方商品
                ->order('update_time desc,poi_sort desc')
                ->select();
        }
        //景点POI
        $spots=Db::name('poi')->where("deleted",0)->where("typeid",'eq',1)->select();


        $summary = db('poi p')
            ->field("count(*) as number,p.typeid")
            ->where($where)->where(['typeid'=>['in',$type_ids]])
            ->group("typeid")
            ->select();
        //统计类型下的POI数量
        foreach ($classify_list as $class_key=>$class_value){
            $classify_list[$class_key]['total_num'] = 0;
            if(!empty($summary)){
                foreach ($summary as $value){
                    if($value['typeid']==$class_value['classify_id']){
                        $classify_list[$class_key]['total_num'] = $value['number'];
                        break;
                    }
                }
            }
        }

        foreach ($poi as $poi_key=>$poi_value){
            $poi[$poi_key]['update_time'] = date("Y-m-d H:i", $poi_value['update_time']);
            $poi[$poi_key]['type'] = '';
            foreach ($classify_list as $class_key=>$class_value){
                if($class_value['classify_id']==$poi_value['typeid']){
                    $poi[$poi_key]['type'] = $class_value['classify_name'];break;
                }
            }
        }

        if($poi){
            $poiname=$poi[0]['name'];
            $poieng_name=$poi[0]['eng_name'];
            $latlng=[$poi[0]['lat'],$poi[0]['lng']];
            $description=$poi[0]['description'];
            $mobile=$poi[0]['mobile'];
            $cooking=$poi[0]['cooking'];
            $ticket=$poi[0]['ticket'];
            $ticketCost=$poi[0]['ticket_cost']?:"";
            $ticketLastAdmin=$poi[0]['ticket_last_admin']?:"";
            $ticketLastUpdtime=$poi[0]['ticket_last_updtime']?:"";
            $shop=$poi[0]['shop'];
            $introduce=$poi[0]['introduce'];
            $open_time=$poi[0]['open_time'];
            $use_time=$poi[0]['use_time'];
            $source=$poi[0]['source'];
            $address=$poi[0]['address'];
            $grade = '';
            if(!empty($poi[0]['grade']) && $poi[0]['grade']>0){
                for ($i=0;$i<$poi[0]['grade'];$i++) {
                    $grade .= "★";
                }
            }
            $remark=$poi[0]['remark'];
            for($x=0;$x<count($spots);$x++){
                if($spots[$x]['name']!=$poiname){
                    $limit = (new GeoHash())->getDistance($poi[0]['lat'],$poi[0]['lng'],$spots[$x]['lat'],$spots[$x]['lng']);
                    if($limit<=100000){
                        array_push($nearspots,[$spots[$x]['name'],round($limit/1000,1),$spots[$x]['id']]);
                    }
                }
            }
            $thumb=explode(',',$poi[0]['thumb']);

            //加入图片库图片
            $imgData = db("poi_images")->where("poi_id",$poi[0]['id'])->where("show",1)->select();
            foreach ($imgData as $k=>$v) {
                $thumb[] = $v['img_src'];
            }

            $city = db("city")->where("id",$poi[0]['groupid'])->find();
            if($city['groupid']==51){//加拿大CAD
                $currency = "C$";
                $currencyName = "加元";
            }else{//美国US
                $currency = "$";
                $currencyName = "美元";
            }

            $ticketPriceData = db("ticketprice")->where("poiid",$poi[0]['id'])->select();

            $breakfast_fee = '';
            $charging_fee = '';
            $service_fee = '';
            $checkin_time = '';
            $price_json = [];
            //当POI为酒店时
            if($poi[0]['typeid']==5){
                $hotelDetail = db("hotel_details")->where("pid",$poi[0]['id'])->find();
                if(!empty($hotelDetail)){
                    $breakfast_fee = !empty($hotelDetail['breakfast_fee']) ? $hotelDetail['breakfast_fee'] : '';//早餐
                    $charging_fee = !empty($hotelDetail['charging_fee']) ? $hotelDetail['charging_fee'] : '';//加人费
                    $service_fee = !empty($hotelDetail['service_fee']) ? $hotelDetail['service_fee'] : '';//服务费
                    $checkin_time = !empty($hotelDetail['checkin_time']) ? $hotelDetail['checkin_time'] : '';//入住时间
                    $price_json = !empty($hotelDetail['price_json']) ? json_decode($hotelDetail['price_json'],true) : '';//价格详情
                }
            }
        }else{
            $latlng=0;
            $description='';
            $poiname='';
            $poieng_name='';
            $mobile='';
            $ticket='';
            $ticketCost='';
            $ticketLastAdmin='';
            $ticketLastUpdtime='';
            $shop='';
            $introduce='';
            $open_time='';
            $use_time='';
            $source='';
            $address='';
            $grade='';
            $remark='';
            $nearspots='';
            $thumb='';
            $cooking='';
            $ticketPriceData = [];
            $currency = '';
            $currencyName = '';
            $breakfast_fee = '';
            $charging_fee = '';
            $service_fee = '';
            $checkin_time = '';
            $price_json = [];
        }

        $this->assign('currency',$currency);
        $this->assign('currencyName',$currencyName);
        $this->assign('ticketPriceData',$ticketPriceData);
        $this->assign('classify_name',$classify_name);
        $this->assign('poiname',$poiname);
        $this->assign('name',$name[0]['name']);
        $this->assign('poieng_name',$poieng_name);
        $this->assign('id',$id);
        $this->assign('poi',$poi);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('cooking',$cooking);
        $this->assign('shop',$shop);
        $this->assign('mobile',$mobile);
        $this->assign('ticket',$ticket);
        $this->assign('ticketCost',$ticketCost);
        $this->assign('ticketLastAdmin',$ticketLastAdmin);
        $this->assign('ticketLastUpdtime',$ticketLastUpdtime);
        $this->assign('grade',$grade);
        $this->assign('introduce',$introduce);
        $this->assign('open_time',$open_time);
        $this->assign('use_time',$use_time);
        $this->assign('source',$source);
        $this->assign('address',$address);
        $this->assign('nearspots',$nearspots);
        $this->assign('thumb',$thumb);
        $this->assign('classify_list',$classify_list);
        $this->assign('remark',$remark);
        $this->assign('breakfast_fee',$breakfast_fee);
        $this->assign('charging_fee',$charging_fee);
        $this->assign('service_fee',$service_fee);
        $this->assign('checkin_time',$checkin_time);
        $this->assign('price_json',$price_json);

        //获取当前城市的信息
        $this->assign('city_info',json_encode($name[0]));
        //获取当前城市的poi的信息
        $this->assign('city_poi_list',json_encode($poi));

        //跳转的新增页面
        $usemap = 'googlemap';
        $china = db('city')->where('eng_name','Chinese Mainland')->find();
        if(!empty($china) && !empty($name[0]['groupid']) && $name[0]['groupid']==$china['id']){
            $usemap = 'amap';
        }
        $this->assign('usemap',$usemap);
        return $this->fetch();
    }

    public function addpoi()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new poiModel();
        //初始化类型和数量统计
        $classify_list = db('classify')->field('classify_id,classify_name')->where(['is_use'=>1])->select();
        $this->assign('classify_list',$classify_list);
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    //将图片来源标记
                    $from = isset($post['from'])&&!empty($post['from'])?$post['from']:"";
                    $content_img = isset($post['thumb'])&&!empty($post['thumb'])?$post['thumb']:"";
                    $this->addSourcePOIImg($id,$content_img,$from);
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $poi = Db::name('poi')->where('id',$id)->select();
                if(!empty($poi)) {
                    if($poi[0]['typeid']==5){
                        $hotelData = db("hotel_details")->where("pid",$id)->find();
                        if(!empty($hotelData)){
                            $hotelData['price_data'] = json_decode($hotelData['price_json'],true);
                        }

                        //当POI为酒店时
                        $poi[0]['breakfast_fee'] = '';
                        $poi[0]['charging_fee'] = '';
                        $poi[0]['service_fee'] = '';
                        $poi[0]['checkin_time'] = '';
                        $poi[0]['price_json'] = '';
                        if($poi[0]['typeid']==5){
                            $hotelDetail = db("hotel_details")->where("pid",$poi[0]['id'])->find();
                            if(!empty($hotelDetail)){
                                $poi[0]['breakfast_fee'] = !empty($hotelDetail['breakfast_fee']) ? $hotelDetail['breakfast_fee'] : '';//早餐
                                $poi[0]['charging_fee'] = !empty($hotelDetail['charging_fee']) ? $hotelDetail['charging_fee'] : '';//加人费
                                $poi[0]['service_fee'] = !empty($hotelDetail['service_fee']) ? $hotelDetail['service_fee'] : '';//服务费
                                $poi[0]['checkin_time'] = !empty($hotelDetail['checkin_time']) ? $hotelDetail['checkin_time'] : '';//入住时间
                                $poi[0]['price_json'] = !empty($hotelDetail['price_json']) ? json_decode($hotelDetail['price_json'],true) : '';//价格详情
                            }
                        }
                    }

                    $this->assign('menu',$poi[0]);
                    $this->assign('thumb',explode(',',$poi[0]['thumb']));
                    $this->assign('groupid',$poi[0]['groupid']);
                    $this->assign('typeid',$poi[0]['typeid']);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $post['mobile']=!empty($post['mobile'])?$post['mobile']:' ';
                if(isset($post['id'])&&empty($post['id'])){
                    //新增操作时的id传值为空
                    unset($post['id']);
                }
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空'],
                    ['lat', 'require', '请根据英文名称提示选择地址'],
                    ['lng', 'require', '请根据英文名称提示选择地址']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    //将图片来源标记
                    $from = isset($post['from'])&&!empty($post['from'])?$post['from']:"";
                    $content_img = isset($post['thumb'])&&!empty($post['thumb'])?$post['thumb']:"";

                    $poiid = db("poi")->getLastInsID();
                    $this->addSourcePOIImg($poiid,$content_img,$from);

                    //新增POI成功 增加管理员积分记录
                    (new KbxOrder())->addAdminScore("POI",$poiid,'新增POI-ID为'.$poiid.'的'.$post['name']);

                    return $this->success('添加成功','admin/poi/index',['id'=>$poiid]);
                }
            } else {
                //非提交操作
                $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;

                $this->assign('groupid',$groupid);
                $this->assign('thumb','');

                return $this->fetch();
            }
        }

        return $this->fetch();
    }

    public function delpoi()
    {
        $model = new poiModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $data['deleted']=1;
        $data['active_delete']=1;
        $city=$model->save($data,['id'=>$id]);

        if(empty($city)) {
            return $this->error('删除失败');
        } else {
            return $this->success('删除成功','',$city);
        }
    }

    public function seemap()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $city=Db::name('city')->where('id',$id)->select();

        if(empty($city)) {
            return $this->error('查看信息失败');
        } else {
            for($x=0;$x<count($city);$x++){
                $city[$x]['thumb']=explode(',',$city[$x]['thumb']);
            }
            return $this->success('查询成功','',$city);
        }
    }

    public function seepoimap()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $spots=Db::name('poi')->where('deleted',0)->where("typeid",'eq',1)->select();

        $poi=Db::name('poi')->where('id',$id)->select();
        $poi[0]['nearspots']=array();
        for($x=0;$x<count($spots);$x++){
            if($spots[$x]['name']!=$poi[0]['name']){
                $limit = (new GeoHash())->getDistance($poi[0]['lat'],$poi[0]['lng'],$spots[$x]['lat'],$spots[$x]['lng']);

                if($limit<=100000){
                    array_push($poi[0]['nearspots'],[$spots[$x]['name'],round($limit/1000,1),$spots[$x]['id']]);
                }
            }
        }

        $thumb = explode(",",$poi[0]['thumb']);

        //加入图片库图片
        $imgData = db("poi_images")->where("poi_id",$id)->where("show",1)->select();
        foreach ($imgData as $k=>$v) {
            $thumb[] = $v['img_src'];
        }
        $poi[0]['thumb'] = implode(",",$thumb);

        $city = db("city")->where("id",$poi[0]['groupid'])->find();
        if($city['groupid']==51){//加拿大CAD
            $currency = "C$";
            $currencyName = "加元";
        }else{//美国US
            $currency = "$";
            $currencyName = "美元";
        }
        $ticketPriceData = db("ticketprice")->where("poiid",$poi[0]['id'])->select();
        $poi[0]['ticketPriceData'] = $ticketPriceData;
        $poi[0]['currency'] = $currency;

        //当POI为酒店时
        $poi[0]['breakfast_fee'] = '';
        $poi[0]['charging_fee'] = '';
        $poi[0]['service_fee'] = '';
        $poi[0]['checkin_time'] = '';
        $poi[0]['price_json'] = '';
        if($poi[0]['typeid']==5){
            $hotelDetail = db("hotel_details")->where("pid",$poi[0]['id'])->find();
            if(!empty($hotelDetail)){
                $poi[0]['breakfast_fee'] = !empty($hotelDetail['breakfast_fee']) ? $hotelDetail['breakfast_fee'] : '';//早餐
                $poi[0]['charging_fee'] = !empty($hotelDetail['charging_fee']) ? $hotelDetail['charging_fee'] : '';//加人费
                $poi[0]['service_fee'] = !empty($hotelDetail['service_fee']) ? $hotelDetail['service_fee'] : '';//服务费
                $poi[0]['checkin_time'] = !empty($hotelDetail['checkin_time']) ? $hotelDetail['checkin_time'] : '';//入住时间
                $poi[0]['price_json'] = !empty($hotelDetail['price_json']) ? json_decode($hotelDetail['price_json'],true) : '';//价格详情
            }
        }

        if(empty($poi)) {
            return $this->error('查看信息失败');
        } else {
            return $this->success('查询成功','',$poi);
        }
    }

    public function addcountry()
    {
        $continentList = (new City())->getContinentList();
        $this->assign('continentList',$continentList);
        return $this->fetch();
    }

    public function airportadmin()
    {
        $citys=array();
        $post = $this->request->post();
        $where['deleted']=0;
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['name'] = ['like', '%' . $post['cityname'] . '%'];
        }
        $city = Db::name('city')->where($where)->select();


        for ($x=0; $x<count($city); $x++) {
            if(!empty($city[$x]['groupid'])&&Db::name('city')->where('deleted',0)->where('id',$city[$x]['groupid'])->select()){
                $wherepoi['groupid']=$city[$x]['id'];
                $wherepoi['typeid']=7;
                $wherepoi['deleted']=0;
                $poi=Db::name('poi')->where($wherepoi)->select();
                if($poi){
                    $city[$x]['poinum']=count($poi);
                }else{
                    $city[$x]['poinum']=0;
                }
                array_push($citys,$city[$x]);
            }

        }
        if($citys){
            $latlng=[$citys[0]['lat'],$citys[0]['lng']];
            $description=$citys[0]['description'];
            $name=$citys[0]['name'];
            $thumb=explode(',',$citys[0]['thumb']);
        }else{
            $latlng=0;
            $description='';
            $name='';
            $thumb='';
        }

        $this->assign('city',$citys);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('name',$name);
        $this->assign('thumb',$thumb);
        return $this->fetch();
    }

    public function airport()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $name=Db::name('city')->where('id',$id)->select();

        $post = $this->request->post();
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['name|eng_name'] = ['like', '%' . $post['cityname'] . '%'];
        }
        $where['groupid']=$id;
        $where['typeid']=7;
        $where['deleted']=0;

        $poi=Db::name('poi')->where($where)->order('create_time desc')->select();

        for($x=0;$x<count($poi);$x++){
            $poi[$x]['update_time']=date("Y-m-d H:i", $poi[$x]['update_time']);
        }
        if($poi){
            $poiname=$poi[0]['name'];
            $poieng_name=$poi[0]['eng_name'];
            $latlng=[$poi[0]['lat'],$poi[0]['lng']];
            $description=$poi[0]['description'];
            $mobile=$poi[0]['mobile'];
            $introduce=$poi[0]['introduce'];
            $thumb=explode(',',$poi[0]['thumb']);
        }else{
            $latlng=0;
            $description='';
            $poiname='';
            $poieng_name='';
            $mobile='';
            $introduce='';
            $thumb="";
        }

        $this->assign('name',$name[0]['name']);
        $this->assign('poiname',$poiname);
        $this->assign('poieng_name',$poieng_name);
        $this->assign('id',$id);
        $this->assign('poi',$poi);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('introduce',$introduce);
        $this->assign('mobile',$mobile);
        $this->assign('thumb',$thumb);
        return $this->fetch();
    }

    public function addairport()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new poiModel();

        if($id > 0) {
            //修改操作

            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空'],
                    ['address', 'require', '地址不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作

                $poi = Db::name('poi')->where('id',$id)->select();
                if(!empty($poi)) {
                    $this->assign('menu',$poi[0]);
                    $this->assign('groupid',$poi[0]['groupid']);
                    $this->assign('thumb',explode(',',$poi[0]['thumb']));
                    $this->assign('typeid',$poi[0]['typeid']);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作

            if($this->request->isPost()) {

                //是提交操作
                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空'],
                    ['address', 'require', '地址不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {


                    return $this->success('添加成功','admin/poi/index');
                }
            } else {
                //非提交操作
                $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;

                $this->assign('groupid',$groupid);
                $this->assign('thumb','');
                return $this->fetch();
            }
        }
        return $this->fetch();
    }

    public function team()
    {
        $citys=array();
        $post = $this->request->post();
        $where['deleted'] =0;
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['name'] = ['like', '%' . $post['cityname'] . '%'];
        }
        $city = Db::name('city')->where($where)->select();


        for ($x=0; $x<count($city); $x++) {
            if(!empty($city[$x]['groupid'])&&Db::name('city')->where('id',$city[$x]['groupid'])->select()){
                $wherepoi['groupid']=$city[$x]['id'];
                $wherepoi['typeid']=8;
                $wherepoi['deleted']=0;
                $poi=Db::name('poi')->where($wherepoi)->select();
                if($poi){
                    $city[$x]['poinum']=count($poi);
                }else{
                    $city[$x]['poinum']=0;
                }
                array_push($citys,$city[$x]);
            }
        }
        if($citys){
            $latlng=[$citys[0]['lat'],$citys[0]['lng']];
            $description=$citys[0]['description'];
            $name=$citys[0]['name'];
            $thumb=explode(',',$citys[0]['thumb']);
        }else{
            $latlng=0;
            $description='';
            $name='';
            $thumb='';
        }

        $this->assign('city',$citys);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('name',$name);
        $this->assign('thumb',$thumb);
        return $this->fetch();
    }

    public function teamlist()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $name=Db::name('city')->where('id',$id)->select();

        $post = $this->request->post();
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['name|eng_name'] = ['like', '%' . $post['cityname'] . '%'];
        }
        if (isset($post['source']) and !empty($post['source'])) {
            $where['source'] = ['like', '%' . $post['source'] . '%'];
        }
        $where['groupid']=$id;
        $where['typeid']=8;
        $where['deleted']=0;
        $poi=Db::name('poi')->where($where)->order('create_time desc')->select();
        for($x=0;$x<count($poi);$x++){
            $poi[$x]['update_time']=date("Y-m-d H:i", $poi[$x]['update_time']);
        }
        if($poi){
            $poiname=$poi[0]['name'];
            $poieng_name=$poi[0]['eng_name'];
            $latlng=[$poi[0]['lat'],$poi[0]['lng']];
            $description=$poi[0]['description'];
            $mobile=$poi[0]['mobile'];
            $introduce=$poi[0]['introduce'];
        }else{
            $latlng=0;
            $description='';
            $poiname='';
            $poieng_name='';
            $mobile='';
            $introduce='';
        }

        $this->assign('name',$name[0]['name']);
        $this->assign('poiname',$poiname);
        $this->assign('poieng_name',$poieng_name);
        $this->assign('id',$id);
        $this->assign('poi',$poi);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('introduce',$introduce);
        $this->assign('mobile',$mobile);
        return $this->fetch();
    }

    public function addteam()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new poiModel();

        if($id > 0) {
            //修改操作

            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $where['name']=$post['name'];
                $where['deleted']=0;

//                if(Db::name('poi')->where($where)->where('id','<>',$id)->select()) {
//                    return $this->error('供应商名称已存在');
//                }


                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作

                $poi = Db::name('poi')->where('id',$id)->select();
                if(!empty($poi)) {
                    $this->assign('menu',$poi[0]);
                    $this->assign('groupid',$poi[0]['groupid']);
                    $this->assign('typeid',$poi[0]['typeid']);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作

            if($this->request->isPost()) {

                //是提交操作
                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $where['name']=$post['name'];
                $where['deleted']=0;

//                if(Db::name('poi')->where($where)->select()) {
//                    return $this->error('供应商名称已存在');
//                }

                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    return $this->success('添加成功','admin/poi/index');
                }
            } else {
                //非提交操作
                $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;

                $this->assign('groupid',$groupid);
                $this->assign('fileid',"");

                return $this->fetch();
            }
        }
        return $this->fetch();
    }

    public function seeteam()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id > 0) {
            $poi = Db::name('poi')->where('id',$id)->find();
            if(!empty($poi)) {
                $filename = Db::name('attachment')->where('id',$poi['fileid'])->field('filename')->find();
                $poi['filename']=$filename['filename'];

                $this->assign('poi',$poi);
                return $this->fetch();
            } else {
                return $this->error('id不正确');
            }
        }
        return $this->fetch();
    }

    public function poisearch()
    {
        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 0;
        if($this->request->isPost()){
            $post = $this->request->post();
        }else{
            $post = Cookie::get('search_poi_form');
        }
        $post['typeid'] = !empty($typeid)?$typeid:0;
        Cookie::set('search_poi_form',$post);
        $name = $post['name']??'';
        $is_stop = $post['is_stop']??'';
        $is_checked = $post['is_checked']??'';
        $groupid = $post['groupid']??'';
        $this->assign('param',$post);

        if ($name) $where['name|eng_name'] = ['like', '%' . trim($name) . '%'];

        if($is_stop!=="") $where['is_stop'] = $is_stop;

        if($groupid!=="") $where['groupid'] = $groupid;

        if($is_checked!=="") $where['is_checked'] = $is_checked;

        $where['deleted']=0;
        //获取分类列表
        $classify_list = db('classify')->field('classify_id,classify_name,classify_en_name')->where(['is_use'=>1])->select();
        $classify_ids = array_column($classify_list,'classify_id');
        if(empty($typeid)){
            $where['typeid'] = ['in',$classify_ids];
        }else{
            $where['typeid'] = [['in',$classify_ids],$typeid];
        }


        //首次加载
        $page = 1;
        $offset = 20;
//        var_dump($where);exit;
        list($list,$pageInfo,$citylist) = $this->getPoiList($where,$page,$offset,$classify_list);
        //统计分类下的POI数量
        $where['typeid'] = ['in',$classify_ids];
        $summary = db('poi p')
            ->field("count(*) as number,p.typeid")
            ->where($where)
            ->group("typeid")
            ->select();
        //统计类型下的POI总数量
        $allnum = 0;
        foreach ($classify_list as $class_key=>$class_value){
            $classify_list[$class_key]['total_num'] = 0;
            if(!empty($summary)){
                foreach ($summary as $value){
                    if($value['typeid']==$class_value['classify_id']){
                        $classify_list[$class_key]['total_num'] = $value['number'];
                        $allnum += $value['number'];
                        break;
                    }
                }

            }
        }
        $this->assign('allnum',$allnum);
        $this->assign('classify_list',$classify_list);
        $this->assign('citylist',$citylist);
        $this->assign('pageInfo',$pageInfo);

        if(!empty($list)){
            //$list = (new CommonAdmin())->setLangByCookie($list,['name'],['eng_name'],true);
            //更新POI列表内容的部分字段
            foreach ($list as $poi_key=>$poi_value){
                $list[$poi_key]['type'] = '';
                $list[$poi_key]['city'] = '';
                //赋值分类名称
                foreach ($classify_list as $class_key=>$class_value){
                    if($class_value['classify_id']==$poi_value['typeid']){
                        $list[$poi_key]['type'] = $class_value['classify_name'];break;
                    }
                }
                //赋值城市名称
                foreach ($citylist as $city_key=>$city_value){
                    if($city_value['id']==$poi_value['groupid']){
                        $list[$poi_key]['city'] = $city_value['name'];break;
                    }
                }
            }
            //首个POI获取附近经纬度
            //获取POI为景点的列表
            $spots = db('poi')->where(['id'=>['neq',$list[0]['id']],'deleted'=>0,'typeid'=>1])->select();
            $nearspots = [];
            if(!empty($list[0]['lat']) && !empty($list[0]['lng'])){
                foreach ($spots as $spot_k=>$spot_v){
                    if(empty($spot_v['lat']) || empty($spot_v['lng'])) continue;
                    $limit = (new GeoHash())->getDistance($list[0]['lat'],$list[0]['lng'],$spot_v['lat'],$spot_v['lng']);
                    if($limit <= 100000){//小于100公里的景点
                        array_push($nearspots,[$spot_v['name'],round($limit/1000,1),$spot_v['id']]);
                    }
                }
            }
            $this->assign('nearspots',$nearspots);
            $this->assign('list',$list);
        }
        return $this->fetch();
    }

    //接口获取POI列表的分页数据
    public function ajaxGetPoiList()
    {
        //获取分页数据
        $post = request()->post();
        $page = $post['page']??1;
        $offset = $post['offset']??20;
        //cookie 获取搜索条件
        $param = Cookie::get('search_poi_form');
        $name = $param['name']??0;
        $groupid = $param['groupid']??0;
        $is_stop = $param['is_stop']??'';
        $is_checked = $param['is_checked']??'';
        $typeid = $param['typeid']??'';
        //未删除标志
        $where['deleted']=0;
        //获取分类列表
        $classify_list = db('classify')->field('classify_id,classify_name,classify_en_name')->where(['is_use'=>1])->select();
        $classify_ids = array_column($classify_list,'classify_id');
        if(empty($typeid)){
            $where['typeid'] = ['in',$classify_ids];
        }else{
            $where['typeid'] = [['in',$classify_ids],$typeid];
        }
        //按名称检索
        if(!empty($name)) $where['name|eng_name'] = ['like', '%' . trim($name) . '%'];
        //按城市检索
        if(!empty($groupid)) $where['groupid'] = $groupid;
        if($is_stop!=="") $where['is_stop'] = $is_stop;
        if($is_checked!=="") $where['is_checked'] = $is_checked;
        //按分类检索
        if(!empty($typeid)) $where['typeid'] = $typeid;
        list($list,$pageInfo) = $this->getPoiList($where,$page,$offset,$classify_list);
        return $this->result(['list'=>$list,'pageInfo'=>$pageInfo],200,'success','json');
    }

    //私有方法 获取poi列表
    private function getPoiList($where,$page,$offset,$classify_list)
    {
        //获取POI列表
        $list = db('poi')->where($where)->order('create_time desc')->page($page,$offset)->select();
        $totalNum = db('poi')->where($where)->order('create_time desc')->count();
        //获取城市列表
        $citylist = db('city')->where(['groupid'=>['neq',0],'deleted'=>0])->field('id,name')->select();
        $china = db('city')->where('eng_name','Chinese Mainland')->find();
        $china_city = db('city')->where('groupid',$china['id'])->column('id');
        //更新POI列表内容的部分字段
        foreach ($list as $poi_key=>$poi_value){
            $list[$poi_key]['update_time'] = date("Y-m-d H:i", $poi_value['update_time']);
            $list[$poi_key]['type'] = '';
            $list[$poi_key]['city'] = '';
            $list[$poi_key]['usemap'] = !empty($china['id'])&&!empty($poi_value['groupid'])&&in_array($poi_value['groupid'],$china_city)?'amap':'googlemap';

            //赋值分类名称
            foreach ($classify_list as $class_key=>$class_value){
                if($class_value['classify_id']==$poi_value['typeid']){
                    $list[$poi_key]['type'] = $class_value['classify_name'];break;
                }
            }
            //赋值城市名称
            foreach ($citylist as $city_key=>$city_value){
                if($city_value['id']==$poi_value['groupid']){
                    $list[$poi_key]['city'] = $city_value['name'];break;
                }
            }
        }

        $pageInfo = [
            'page'=>$page,
            'offset'=>$offset,
            'totalNum'=>$totalNum,
            'totalPage'=>ceil($totalNum/$offset),
        ];
        return [$list,$pageInfo,$citylist,$classify_list];
    }


    public function recovery(){
        $data= db('city')->where('deleted',1)->paginate(15);
        if (request()->isPost()){
            $post=request()->post();
            if ($post['bs']=='recovery'){
                if (db('city')->where('id',$post['id'])->update(['deleted'=>0])) {
                    return $this->success('恢复成功');
                }else{
                    return $this->error('恢复失败');
                }
            }
            if ($post['bs']=='del'){
                if (db('city')->where('id',$post['id'])->delete()){
                    return $this->success('删除成功');
                }else{
                    return $this->error('删除失败');
                }
            }
        }



        $this->assign('data',$data);
        return view();
    }

    //ajax查询供应商名单
    //by suley
    public function getPoi($id,$typeid=8){
        if( $typeid==8 ){//查询supplier供应商

        }
        $where['groupid']=$id;
        $where['typeid']=$typeid;
        $where['deleted']=0;
        $poi = Db::name('poi')->where($where)->field("id,name")->select();
        return $poi;
    }

    //新增城市关联Viator城市destid
    public function correlation()
    {
        $post = $this->request->post();
        $where = [];
        if (isset($post['cityname']) and !empty($post['cityname'])) {
            $where['c.id|c.name|c.ename'] = ['like', '%' . trim($post['cityname']) . '%'];
        }
        $city = Db::name('dclcity c')
            ->join('dclcity country','country.id=c.pid','left')
            ->where($where)
            ->field('c.*,country.name as pname')
            ->select();
        foreach ($city as $key=>$value){
            switch ($value['type']){
                case 'COUNTRY':
                    $city[$key]['name'] = "【国家】".$city[$key]['name'];break;
                case 'CITY':
                    $city[$key]['name'] = "【城市】".$city[$key]['name'];break;
                case 'REGION':
                default:
                    break;
            }
        }
        $this->assign('city',$city);
        return $this->fetch();
    }

    //扩展 poi评论 by wtt 2019-04-01
    public function poiCommentList()
    {
        $where = [];
        if(request()->isPost()){
            $post= request()->post();
            if (isset($post['poi_id']) and $post['poi_id'] > 0) {
                $where['poi_id'] = $post['poi_id'];
            }
            if (isset($post['poi_name']) and $post['poi_name'] !=='') {
                $where['poi_name'] = $post['poi_name'];
            }
            //订单类型
            if (isset($post['is_good']) && $post['is_good']!==''){
                $where['is_good'] = $post['is_good'];
            }
            //价格设置
            if (isset($post['is_show']) && $post['is_show']!==''){
                $where['is_show'] = (string)$post['is_show'];
            }
            //置顶设置
            if (isset($post['is_top']) && $post['is_top']!==''){
                $where['is_top'] = $post['is_top'];
            }
            //是否重置
            if (isset($post['reset']) && $post['reset']==1){
                $where = [];
            }
            Cookie::set('wheres',$where);
        }else{
            $page=request()->param('page');
            if(!empty($page)){
                $where=Cookie::get('wheres');
            }else{
                Cookie::set('wheres',$where);
            }
        }
        $poi_name = isset($where['poi_name'])?$where['poi_name']:"";
        unset($where['poi_name']);

        $offset = 15;
        $list = db("poi_comment pc")
            ->field('pc.*,m.member_nickname as username,th.filepath as userface,poi.name as poi_name')
            ->join("tplay_member m","m.member_id=pc.user_id",'LEFT')
            ->join("tplay_attachment th","th.id=m.thumb",'LEFT')
            ->join("tplay_poi poi","poi.id=pc.poi_id",'LEFT')
            ->where($where)
            ->order('pc.create_at desc')
            ->paginate($offset);
        $data = $list->toArray()['data'];
        if(!empty($data)){
            foreach ($data as $key=>$value){
                if(!empty($value['content_img'])){
                    $data[$key]['content_img'] = explode(",",$value['content_img']);
                }
                $data[$key]['create_at'] = date("Y-m-d H:i:s",$value['create_at']);
            }
        }
        isset($poi_name) && $poi_name!='' && $where['poi_name']=$poi_name;
        $this->assign("where",$where);
        $this->assign("data",$data);
        $this->assign("list",$list);

        //获取poi列表
        $poi_where['deleted'] = 0;
        $poilist = db("poi")->field("id,name")->where($poi_where)->select();
        $this->assign("poilist",$poilist);
        return $this->fetch();
    }

    //删除poi
    public function delPoiComment()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'缺少id参数']);
        }

        $id = $post['id'];
        $poiComment = db('poi_comment')->find($id);
        if(empty($poiComment)){
            return json(['code'=>-1,'msg'=>'poi信息有误']);
        }
        $res = db('poi_comment')->delete($id);
        if($res){
            //修改poi的总评论数和总评论分
            $poi = db("poi")->find($poiComment['poi_id']);
            db("poi")->where('id',$poiComment['poi_id'])->update([
                'total_comment_num'=>$poi['total_comment_num']-1,
                'total_score'=>$poi['total_score']-$poiComment['score']

            ]);
            return json(['code'=>200,'msg'=>'删除评论成功',]);
        }else{
            return json(['code'=>-1,'msg'=>'删除评论失败']);
        }

    }

    //修改是否隐藏poi评论
    public function modifyShowComment()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'请填写id参数']);
        }

        $is_show = isset($post['show'])?$post['show']:"0";

        $res = db("poi_comment")->where("comment_id",$post['id'])->update(['is_show'=>$is_show]);
        if($res!==false){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

    //修改是否精选poi评论
    public function modifyGoodComment()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'请填写id参数']);
        }

        $is_good = isset($post['good'])?$post['good']:"0";

        $res = db("poi_comment")->where("comment_id",$post['id'])->update(['is_good'=>$is_good]);
        if($res!==false){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

    //修改是否置顶poi评论
    public function modifyTopComment()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'请填写id参数']);
        }

        $is_top = isset($post['top'])?$post['top']:"0";

        $res = db("poi_comment")->where("comment_id",$post['id'])->update(['is_top'=>$is_top]);
        if($res!==false){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

    //修改是否poi评论匿名
    public function modifyAnonymousComment()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'请填写id参数']);
        }

        $is_anonymous = isset($post['anonymous'])?$post['anonymous']:"0";

        $res = db("poi_comment")->where("comment_id",$post['id'])->update(['is_anonymous'=>$is_anonymous]);
        if($res!==false){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

    //查询poi
    public function searchPoi()
    {
        $post = request()->post();
        $where['deleted'] = 0;
        $list = [];
        if(isset($post['key'])){
            $key = $post['key'];
            $where['name'] = ['like','%'.$key.'%'];
            $list = db("poi")->where($where)->field("id,name")->order("id desc")->select();
        }else{
            $list = db("poi")->where($where)->field("id,name")->order("id desc")->select();
        }

        return json(['code'=>200,'msg'=>'获取列表成功','data'=>$list]);
    }

    //图片库
    public function poiImage(){
        $poi_id = input("id");
        $where['poi_id'] = $poi_id;
        $imgArr = db("poi_images")->where($where)->order("show desc,id desc")->paginate(20);

        $this->assign('poi_id',$poi_id);
        $this->assign('imgArr',$imgArr);
        return $this->fetch();
    }

    public function changeImgShow(){
        $post= request()->post();
        $id = $post['id'];
        $key = $post['key'];
        if($key==1){
            $show = 0;
        }else{
            $show = 1;
        }

        $where['id'] = $id;
        $res = db("poi_images")->where($where)->update(['show'=>$show]);

        if($res){
            return $this->success('使用成功');
        }else{
            return $this->error('使用失败');
        }
    }

    public function upImg(){
        $post= request()->post();
        $data['poi_id'] = $post['poi_id'];
        $data['img_src'] = $post['src'];

        $res = db("poi_images")->insert($data);
        $id = Db::name('poi_images')->getLastInsID();
        $img = db("poi_images")->where("id",$id)->find();

        if($res){
            return $this->success('上传成功','',$img);
        }else{
            return $this->error('上传失败');
        }
    }
    //二级联动
    public function getPoiByCity()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>"缺少参数id"]);
        }

        $poi = db('poi')->field("id,name")->where(['deleted'=>0,'groupid'=>$post['id']])->select();
        return json(['code'=>200,'msg'=>'获取成功','data'=>$poi]);
    }
    //虚拟用户评论
    public function virtualcomment()
    {
        if(request()->isPost()){
            $post = request()->post();
            if(!isset($post['poi'])){
                return json(['code'=>-1,'msg'=>'参数有误']);
            }
            $poi = db("poi")->find($post['poi']);
            if(empty($poi)){
                return json(['code'=>-1,'msg'=>'poi信息不存在']);
            }
            if(!isset($post['content'])){
                return json(['code'=>-1,'msg'=>'请添加评论内容']);
            }

            $score = isset($post['score'])?$post['score']:0;
            $create_time = isset($post['time'])?strtotime($post['time']):time();
            $anonymous = isset($post['anonymous'])?$post['anonymous']:1;
            if($anonymous==0){
                $user_id = $this->addCommentUser($post);
                if(is_array($user_id)){//报错
                    return json($user_id);
                }
            }else{
                $user_id = 0;
            }
            if(isset($post['other_images']) && !empty($post['other_images'])){
                $content_img = array_filter(explode(",",$post['other_images']));
                $content_img = implode(",",$content_img);
            }else{
                $content_img = '';
            }
            $ip = request()->ip();
            //开启事务
            db::startTrans();
            $insert = [
                'user_id'=>$user_id,
                'is_anonymous'=>$anonymous,
                'poi_id'=>$post['poi'],
                'content'=>$post['content'],
                'score'=>$score,
                'content_img'=>$content_img,
                'create_at'=>$create_time,
                'from'=>'admin',
                'ip'=>$ip
            ];
            $res = db('poi_comment')->insert($insert);
            $comment_id = db('poi_comment')->getLastInsID();
            if($res){
                try{
                    //更新poi的评价总分和评价总人数
                    db('poi')->where('id',$post['poi'])->update([
                        'total_score'=>$poi['total_score']+$score,
                        'total_comment_num'=>$poi['total_comment_num']+1
                    ]);
                    //增加poi图片库
                    (new PController())->addPoiCommentImgs($comment_id,$content_img,'admin');
                    //赠送积分
                    if($user_id){
                        (new PController())->addIntegrationByPOIComment($user_id);
                    }
                    //成功提交
                    db::commit();
                    return json(['code'=>200,'msg'=>'评论成功']);
                }catch(\Exception $e){
                    db::rollback();
                    return json(['code'=>-1,'msg'=>'评论失败']);
                }
            }else{
                db::rollback();
                return json(['code'=>-1,'msg'=>'评论失败']);
            }

        }else{
            $city = Db::name('city')->field("id,name")->where(['deleted'=>0,'groupid'=>['neq',0]])->select();
            $this->assign("city",$city);
            return $this->fetch();
        }
    }

    //添加虚拟用户评论
    public function addCommentUser($post)
    {
        $model = new MemberModel();

        $post['member_type_id'] = 1;//会员等级为1     普通会员
        $post['member_email'] = "kbx_".time()."@test.com";
        $post['creattime'] = time();
        $post['updatetime'] = time();
        $post['is_test'] = 1;//是否为虚拟用户
        //*******************************************************
        //验证昵称是否存在
        $nickname = db("member")->where('member_nickname', $post['member_nickname'])->select();
        if (!empty($nickname)) {
            return ['code'=>-1,'msg'=>'昵称已被占用'];
        }
        if (false == $model->allowField(true)->save($post)) {
            return ['code'=>-1,'msg'=>'添加用户失败'];
        } else {
            $member_id = $model->getLastInsID();
            return $member_id;//插入的虚拟用户ID
        }
    }
    //修改是否暂停poi前端显示
    public function modifyStopPoi()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'请填写id参数']);
        }

        $is_stop = isset($post['stop'])?$post['stop']:"0";

        $res = db("poi")->where("id",$post['id'])->update(['is_stop'=>$is_stop]);
        if($res!==false){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

    //导入poi
    public function exportpoi()
    {
        $request = request()->param();
        $page = isset($request['page'])?$request['page']:1;
        $offset = isset($request['offset'])?$request['offset']:30;
        $param = ["page=$page","countPerPage=$offset"];

        $post = request()->post();
        if(!empty($post)){
            Cookie::set("poi_param",$post);
        }else{
            $post = Cookie::get("poi_param");
        }
        $cityCode = isset($post['cityCode'])?$post['cityCode']:"";
        $cateType = isset($post['cateType'])?$post['cateType']:"";

        if(!empty($cityCode)){
            $param[] = "cityCode=$cityCode";
        }
        if(!empty($cateType)){
            $param[] = "cateType=$cateType";
        }

        if(!empty($param)){
            $param_str = "?".implode("&",$param);
        }else{
            $param_str = "";
        }
        //请求城市的接口
        $third_city_url = "https://d.kwibon.cn/wechatbot/api/cities/tripadvisor";
        $thirdCitylist = Common::http($third_city_url);
        $thirdCitylist = json_decode($thirdCitylist,true);
        $third_poi_url  = "https://d.kwibon.cn/wechatbot/api/pois/tripadvisor".$param_str;
        $ThirdPoilist  = Common::http($third_poi_url);
        $ThirdPoilist  = json_decode($ThirdPoilist,true);

        $model['total']=$ThirdPoilist['total'];
        $model['offset']=$offset;
        $model['page']=$page;
        $model['last_page']=ceil($ThirdPoilist['total']/$offset);
        $list = $ThirdPoilist['pois'];
        if(!empty($list)){
            foreach ($list as $key=>$value){
                $list[$key]["categories"] = implode(",",$value['categories']);
                $list[$key]["createdAt"] = date("Y-m-d H:i:s",strtotime($value['createdAt']));
                $value['rating'] = isset($value['rating'])?$value['rating']:"";
                $list[$key]["rating"] = explode(",",str_replace("，",",",$value['rating']))[0];
                $list[$key]["poiinfo"] = db("poi")->where(['link_source'=>$value['urlId']])->find();
            }
        }
        $this->assign('thirdcity',$thirdCitylist);
        $this->assign('list',$list);
        $this->assign('json_list',json_encode($list));
        $this->assign('model',$model);
        $this->assign('post',$post);

        $ourcity = Db::name('city')->where(['deleted'=>0,'groupid'=>['neq',0]])->order("sort_weight desc")->select();
        $this->assign('ourcity',$ourcity);

        return $this->fetch('');
    }

    //获取上传的图片并上传至OSS
    public  function uploadExportImg()
    {
        $post = request()->post();
        if(empty($post) || !isset($post['imgs']) || !is_array($post['imgs'])){
            return json(['code'=>-1,'msg'=>"请选择图片资源"]);
        }
        $imgs = $post['imgs'];
        $result = [];
        foreach ($imgs as $key=>$value){
            if(!empty($value)){
//                $water = ['type'=>'image'];//图片水印
                $ossimgurl = (new OSSApi())->saveRemoteImgToOSS($value,0,1,0.8,['type'=>'text']);
                if($ossimgurl){
                    $result[] = $ossimgurl;
                }
            }
        }

        return json(['code'=>200,'msg'=>'上传成功','data'=>$result]);
    }

    //poi图片入库标记来源（版权问题）
    public function addSourcePOIImg($poi_id,$content_img,$link_source=""){
        if(!empty($content_img) && !empty($poi_id)){
            $imgs = array_filter(explode(",",$content_img));
            if(!empty($imgs)){
                $insert_data = [];
                foreach ($imgs as $k=>$v){
                    $insert_data[] = [
                        'poi_id'=>$poi_id,
                        'img_src'=>$v,
                        'source'=>$link_source
                    ];
                }
                if(!empty($insert_data)){
                    db("poi_images")->insertAll($insert_data);
                }
            }
        }
    }

    //获取poi详情
    public function getPOIInfo()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            return json(['code'=>-1,'msg'=>'缺少poiid参数']);
        }

        $poiinfo = db("poi")->field(['name','eng_name','address','description','introduce','mobile','open_time','source','ticket','ticket_cost','ticket_last_admin','ticket_last_updtime','lat','lng'])->find($post['id']);
        $ticketprice = db("ticketprice")->where("poiid",$post['id'])->select();
        $tablename = $post['table']??"pactive";
        if(!empty($post['active_id'])){
            $active_id = $post['active_id'];
            $pactive = db($tablename)->where("id",$active_id)->field("activeType,ticket_status,ticket_json,self_supplier_ticket")->find();
            if(!empty($pactive['ticket_json'])){
                $ticket_json = json_decode($pactive['ticket_json'],true);
            }else{
                $ticket_json = [];
            }
            return json([
                'code'=>200,
                'msg'=>'获取成功',
                'data'=>$poiinfo,
                'ticket'=>$ticketprice,
                'ticket_status'=>$pactive['ticket_status'],
                'ticket_json'=>$ticket_json,
                'self_supplier_ticket'=>$pactive['self_supplier_ticket'],
                'activeType'=>$pactive['activeType']]);
        }else{
            return json([
                'code'=>200,
                'msg'=>'获取成功',
                'data'=>$poiinfo
            ]);
        }
    }

    //迁移城市
    public function changeCity()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new poiModel();
        if($id > 0) {
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $post['update_time'] = time();
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/poi/poisee?id='.$post['groupid']);
                }
            } else {
                //非提交操作
                $poi = Db::name('poi')->where('id',$id)->find();
                $where['deleted'] = 0;
                $where['type'] = 'CITY';
                $city = db("city")->where($where)->select();
                if(!empty($poi)) {
                    $this->assign('id',$id);
                    $this->assign('city',$city);
                    $this->assign('groupid',$poi['groupid']);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else {
            return $this->error('id不正确');
        }
    }

    //门票配置
    public function addticket()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new poiModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $post['ticket_last_updtime'] = date("Y-m-d H:i:s");
                $admin_id = Cookie::get('admin');
                $adminInfo = db::name('admin')->find($admin_id);
                $post['ticket_last_admin'] = !empty($adminInfo['nickname']) ? $adminInfo['nickname'] : '';

                db("ticketprice")->where("poiid",$id)->delete();

                $ticketData = $post['ticketData'];
                $currencyCode = $post['currencyCode'];
                if(!empty($ticketData)){
                    $ticketDataArr = explode(",",$ticketData);
                    if(!empty($ticketDataArr)){
                        $insertData = [];
                        $default = 0;
                        foreach ($ticketDataArr as $key=>$value) {
                            $ticketPriceData = explode("_",$value);
                            $ticketPriceName = $ticketPriceData[0];
                            $ticketSalePrice = $ticketPriceData[1];
                            $ticketCostPrice = $ticketPriceData[2];
                            $ticketDefault = !empty($ticketPriceData[3]) ? $ticketPriceData[3] : 0;
                            $ticketChargeType = !empty($ticketPriceData[4]) ? $ticketPriceData[4] : 1;
                            if($ticketDefault>0){
                                $default = $ticketDefault;
                            }
                            $insertData[]  = [
                                'poiid'=>$id,
                                'name'=>$ticketPriceName,
                                'sale_price'=>$ticketSalePrice,
                                'cost_price'=>$ticketCostPrice,
                                'currency'=>$currencyCode,
                                'default'=>$ticketDefault,
                                'charge_type'=>$ticketChargeType
                            ];

                        }
                        if($default<1 && count($insertData)>0){
                            $insertData[0]['default'] = 1;
                        }
                        $ticketRes = db("ticketprice")->insertAll($insertData);
                    }
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功');
                }
            } else {
                //非提交操作
                $poi = Db::name('poi')->where('id',$id)->find();
                if(!empty($poi)) {
                    $currency = "$";
                    $currencyCode = "USD";
                    $currencyName = "美元";
                    if(!empty($poi['groupid'])){
                        $groupid = $poi['groupid'];
                        $city = db("city")->where("id",$groupid)->find();
                        if(!empty($city['groupid'])){
                            $country = db("city")->where("id",$city['groupid'])->find();
                            if(!empty($country)){
                                $currency = $country['currency_symbol'];
                                $currencyCode = $country['currency_code'];
                                $currencyName = $country['currency_name'];
                            }
                        }
                    }

                    $ticketPriceData = db("ticketprice")->where("poiid",$id)->select();

                    //供应商   不能放上面，引入类构造方法会过滤html标签
                    list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
                    $this->assign('supplier',$supplier);
                    $this->assign('kbx_url',config('kbx_url'));


                    $this->assign('ticketPriceData',$ticketPriceData);
                    $this->assign('currencyCode',$currencyCode);
                    $this->assign('currencyName',$currencyName);
                    $this->assign('currency',$currency);
                    $this->assign('menu',$poi);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            return $this->error('id不正确');
        }
    }


    //酒店列表
    public function hotellist(){
        $post = $this->request->post();
        $where = [];
        if (!empty($post['name'])) {
            $where['h.name'] = ['like','%'.$post['name'].'%'];
        }
        if (!empty($post['area'])) {
            $where['h.area'] = $post['area'];
        }
        if (isset($post['rank']) && $post['rank']!=='') {
            $where['h.rank'] = $post['rank'];
        }

        $hotelData = db("hotel_details")
            ->alias("h")
            ->join("poi p","p.id=h.pid","left")
            ->where("p.typeid",5)
            ->where("p.import_flag",1)
            ->where($where)
            ->field("p.source,h.*")
            ->select();

        foreach ($hotelData as $key=>$value) {
            $hotelData[$key]['price_json'] = !empty($value['price_json']) ? json_decode($value['price_json'],true) : '';
        }

        $this->assign('wherelist',$post);
        $this->assign('hotelData',$hotelData);

        return $this->fetch();
    }

    //审核的POI
    public function checkPoiInfo()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $is_checked = $post['is_checked']??0;
        $poi = db('poi')->find($id);
        if(empty($id) || empty($poi)) return $this->error('poi信息错误');

        $res = db('poi')->where('id',$id)->update([
            'is_checked'=>$is_checked,
            'checked_time'=>time(),
            'checked_admin'=>Cookie::get('admin')
        ]);

        if($res){
            return $this->success("修改成功");
        }else{
            return $this->success("修改失败");
        }
    }

    //适用手机版新增POI页面
    public function addsimplepoi()
    {
        //初始化类型和数量统计
        $classify_list = db('classify')->field('classify_id,classify_name')->where(['is_use'=>1])->select();
        $this->assign('classify_list',$classify_list);
        $cityList = db('city')->where("type","CITY")->field("id,name")->select();
        $this->assign("cityList",$cityList);
        return $this->fetch();
    }

    //保存手机版新增POI数据
    public function updsimplepoi()
    {
        $post = request()->post();
        $model=new poiModel();

        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $validate = new \think\Validate([
            ['name', 'require', '名称不能为空'],
            ['lat', 'require', '请根据英文名称提示选择地址'],
            ['lng', 'require', '请根据英文名称提示选择地址']
        ]);
        //验证部分数据合法性
        if (!$validate->check($post)) {
            $this->error('提交失败：' . $validate->getError());
        }

        $img = (new PoiApi())->getGoogleMapImgByPOI($post);
        $img = json_decode($img,true);
        if(!empty($img) && isset($img['img']) && !empty($img['img'])){
            $post['map_thumb_img'] = (new OSSApi())->saveRemoteImgToOSS($img['img']);
        }else{
            $post['map_thumb_img'] = "";
        }
        //2019 07 24 增加门票成本 门票最后一次修改时间 门票最后一次修改人
        $post['ticket_last_updtime'] = date("Y-m-d H:i:s");
        $admin_id = Cookie::get('admin');
        $adminInfo = db::name('admin')->find($admin_id);
        $post['ticket_last_admin'] = $adminInfo['nickname']??"";
        if(false == $model->allowField(true)->save($post)) {
            return $this->error('添加失败');
        } else {
            $poiid = db()->getLastInsID();
            return $this->success('添加成功','',['id'=>$poiid]);
        }
    }

    //高德地图新增POI
    public function addNewPoiByAmap()
    {
        $id = input('id',0);
        $model=new poiModel();
        if($this->request->isPost()){
            //ajax 操作
            if($id>0){
                //修改
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空'],
                    ['lat', 'require', '请填写地址并选择'],
                    ['lng', 'require', '请填写地址并选择'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $post['map_thumb_img'] = (new Common())->getAMapImgByLocation($post['lng'].','.$post['lat']);
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    //将图片来源标记
                    $from = isset($post['from'])&&!empty($post['from'])?$post['from']:"";
                    $content_img = isset($post['thumb'])&&!empty($post['thumb'])?$post['thumb']:"";
                    $this->addSourcePOIImg($id,$content_img,$from);
                    return $this->success('修改成功', 'admin/menu/index');
                }
            }else{
                //新增
                $post = $this->request->post();
                $post['mobile']=!empty($post['mobile'])?$post['mobile']:' ';
                if(isset($post['id'])&&empty($post['id'])){
                    //新增操作时的id传值为空
                    unset($post['id']);
                }
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '名称不能为空'],
                    ['lat', 'require', '请填写地址并选择'],
                    ['lng', 'require', '请填写地址并选择']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $post['map_thumb_img'] = (new Common())->getAMapImgByLocation($post['lng'].','.$post['lat']);
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    //将图片来源标记
                    $from = isset($post['from'])&&!empty($post['from'])?$post['from']:"";
                    $content_img = isset($post['thumb'])&&!empty($post['thumb'])?$post['thumb']:"";

                    $poiid = db("poi")->getLastInsID();
                    $this->addSourcePOIImg($poiid,$content_img,$from);

                    //新增POI成功 增加管理员积分记录
                    (new KbxOrder())->addAdminScore("POI",$poiid,'新增POI-ID为'.$poiid.'的'.$post['name']);

                    return $this->success('添加成功','admin/poi/index',['id'=>$poiid]);
                }
            }
        }else{
            //读取操作
            //初始化类型和数量统计
            $classify_list = db('classify')->field('classify_id,classify_name')->where(['is_use'=>1])->select();
            $this->assign('classify_list',$classify_list);
            if($id>0){
                //修改页面
                $poi = db('poi')->find($id);
                if(empty($poi)) return $this->error('POI信息错误');
                if($poi['typeid']==5){
                    $hotelDetail = db("hotel_details")->where("pid",$id)->find();
                    if(!empty($hotelDetail)){
                        $poi['breakfast_fee'] = !empty($hotelDetail['breakfast_fee']) ? $hotelDetail['breakfast_fee'] : '';//早餐
                        $poi['charging_fee'] = !empty($hotelDetail['charging_fee']) ? $hotelDetail['charging_fee'] : '';//加人费
                        $poi['service_fee'] = !empty($hotelDetail['service_fee']) ? $hotelDetail['service_fee'] : '';//服务费
                        $poi['checkin_time'] = !empty($hotelDetail['checkin_time']) ? $hotelDetail['checkin_time'] : '';//入住时间
                        $poi['price_json'] = !empty($hotelDetail['price_json']) ? json_decode($hotelDetail['price_json'],true) : '';//价格详情
                    }
                }

                $this->assign('menu',$poi);
                $this->assign('groupid',$poi['groupid']);
                $this->assign('typeid',$poi['typeid']);
                return $this->fetch();
            }else{
                //新增页面
                $this->assign('groupid',input('groupid',0));
                return $this->fetch();
            }
        }
    }
}
